layui.define(['form','autocomplete','supplier','supplierBank','staticData'], function (exports) {
    var $ = layui.$, form = layui.form, com = layui.com,
        autocomplete = layui.autocomplete,
        supplier = layui.supplier,
        supplierBank = layui.supplierBank,
        staticData = layui.staticData,
        request = layui.request,
        search = layui.router().search,
        bankFee=0.0
        ,fn = {
            async initBaseData(){
                // 付款方式
                let paymentTermData = await staticData.getPaymentTermData(),$paymentTerm = $('#pay-apply-payment-term');
                com.fullSelect({
                    elem:$paymentTerm,
                    data:paymentTermData
                });
                form.render('select', 'form-pay-apply');
                // 收款银行
                request.get('/scm/subjectBank/selectEnableBanks').then(res =>{
                    let bh = [];
                    $.each(res.data || [],function (i,o) {
                        bh.push('<p>'+(i+1)+' 开户行：'+o.name+' 银行账号：'+o.account+' '+o.subjectName+'</p>');
                    });
                    $('#subjectBank').html(bh.join(''));
                });
                // 供应商模糊查询
                autocomplete.render({
                    elem: $("#pay-app-payee-name"),
                    url: '/scm/client/supplier/vague',
                    template_txt: '{{d.name}}',
                    template_val: '{{d.name}}',
                    ajaxParams: {
                        type: 'post',
                        contentType: 'application/x-www-form-urlencoded'
                    },
                    request: {
                        keywords: 'name'
                    },
                    onselect:function (da) {
                        fn.fullBankInfo();
                    }
                });
                // 供应商银行模糊查询
                autocomplete.render({
                    elem: $("#pay-app-payee-bank-name"),
                    url: '/scm/client/supplierBank/vague',
                    template_txt: '{{d.name}}',
                    template_val: '{{d.name}}',
                    ajaxParams: {
                        type: 'post',
                        contentType: 'application/x-www-form-urlencoded',
                    },
                    dynamicData:function () {
                        return {
                            'supplierName':$("#pay-app-payee-name").val()
                        }
                    },
                    request: {
                        keywords: 'bankName'
                    },
                    onselect:function (da) {
                        fn.fullBankInfo();
                    }
                });

            }
            ,async load(){
                await fn.initBaseData();
                let orderId = search.id;
                if(com.isEmpty(orderId)){
                    layer.msg('请选择您要付汇的订单');
                    history.back();
                    return;
                }
                request.postForm('/scm/client/payment/initApply',{'id':orderId}).then(res =>{
                    var data = res.data,payment=data.payment,members=data.members;
                    form.val("form-pay-apply",payment);
                    $('.exchangeRate').html(payment.exchangeRate);
                    var ohtml = [];
                    $.each(members || [],function (i,o){
                        ohtml.push('<tr>');
                        ohtml.push('<td class="t-a-c">'+(i+1)+'</td>');
                        ohtml.push('<td class="t-a-c">'+o.docNo+'</td>');
                        ohtml.push('<td class="t-a-c">'+o.orderDate+'</td>');
                        ohtml.push('<td>&nbsp;&nbsp;'+o.supplierName+'</td>');
                        ohtml.push('<td class="t-a-r" totalPrice="'+o.totalPrice+'">'+com.formatCurrency(o.totalPrice)+'&nbsp;&nbsp;</td>');
                        ohtml.push('<td class="t-a-c">'+o.currencyName+'</td>');
                        ohtml.push('<td class="t-a-r" applyPayVal="'+(Math.round((o.totalPrice - o.applyPayVal)*100)/100)+'">'+com.formatCurrency(o.totalPrice - o.applyPayVal)+'&nbsp;&nbsp;</td>');
                        ohtml.push('<td><input type="hidden" LIST name="orderId" value="'+o.id+'"/><input type="hidden" LIST name="orderNo" value="'+o.docNo+'"/><input type="text" LIST class="layui-input required" name="applyPayVal" onblur="layui.payApply.calculationAll()" NUMBER CLEARZERO value="'+(Math.round((o.totalPrice - o.applyPayVal)*100)/100)+'"/></td>');
                        ohtml.push('<td class="t-a-c"><a href="javascript:" title="删除" zmark-event="layui.payApply.removeRow"><i class="iconfont iconhuishou f14"></i></a></td></tr>');
                    });
                    $('#pay-apply-order-body').html(ohtml.join(""));
                    // 计算手续费
                    fn.calculationFee();
                    // 金额统计
                    fn.calculationAll();
                }).catch((e)=>{
                    history.back();
                });
            }
            ,calculationAll(){
                var ttotalPrice = 0.0,tpayVal = 0.0,rpayVal = 0.0;
                $.each($('td[totalPrice]'),function (i,o) {
                    ttotalPrice += parseFloat($(o).attr('totalPrice'))
                })
                $.each($('td[applyPayVal]'),function (i,o) {
                    tpayVal += parseFloat($(o).attr('applyPayVal'))
                })
                $.each($('input[name="applyPayVal"]'),function (i,o) {
                    if(com.isEmpty($(o).val())){
                        $(o).val('0');
                    }
                    rpayVal += parseFloat($(o).val())
                })
                $('.ttotalPrice').html(com.formatCurrency(ttotalPrice));
                $('.tpayVal').html(com.formatCurrency(tpayVal));
                $('.rpayVal').html(com.formatCurrency(rpayVal));
                $('#pay-apply-account-value').val(com.formatCurrency(rpayVal));

                var payCny = Math.round(rpayVal*parseFloat($('#pay-app-exchange-rate').val())*100)/100;
                $('.payCny').html(com.formatCurrency(payCny));
                $('.handlingFee').html(com.formatCurrency(bankFee));
                $('.payTotalCny').html(com.formatCurrency(payCny+bankFee));
            }
            ,removeRow(othis){
                var $per = othis.parent().parent();
                $per.remove();
                fn.calculationAll();
            }
            ,supplierManage(){
                supplier.add(function (sup) {
                    form.val('form-pay-apply', {'payeeName': sup.name});
                    fn.fullBankInfo();
                });
            }
            ,supplierBankManage(){
                supplierBank.show('',$('#pay-app-payee-name').val(),function (sb) {
                    form.val('form-pay-apply', {'payeeBankName': sb.name});
                    fn.fullBankInfo();
                });
            }
            ,async fullBankInfo(){
                let payeeName = $('#pay-app-payee-name').val(),payeeBankName = $('#pay-app-payee-bank-name').val(),fullData={
                    payeeBankName:'',payeeBankAccountNo:'',swiftCode:'',payeeBankAddress:''
                };
                if(com.isNotEmpty(payeeName)&&com.isNotEmpty(payeeBankName)){
                    await request.postForm('/scm/client/supplierBank/getSupplierBankInfo',{supplierName:payeeName,bankName:payeeBankName}).then(res=>{
                       if(res.data!=null){
                           fullData={
                               payeeBankName:res.data.name,payeeBankAccountNo:res.data.account,swiftCode:res.data.swiftCode,payeeBankAddress:res.data.address
                           };
                       }
                    });
                };
                form.val('form-pay-apply', fullData);
                fn.calculationFee();
            }
            ,calculationFee(){
                let params = $('#form-pay-apply').serializeJson();
                params.orderId=$($('input[name="orderId"]')[0]).val();
                request.get('/scm/paymentAccount/calculationFee',params).then(res =>{
                    bankFee = res.data;
                    $('.handlingFee').html(com.formatCurrency(bankFee));
                    $('.payTotalCny').html(com.formatCurrency(parseFloat($('.payCny').text().replace(/,/g,''))+bankFee));
                });
            }
            ,saveApply(){
                if(!com.validateForm($('#form-pay-apply'))){return;}
                if(!com.validateForm($('#form-pay-apply-order'))){return;}
                let payment = $('#form-pay-apply').serializeJson(),orders = com.jsonList($('#form-pay-apply-order').serializeJson());
                if(orders==null||orders.length==0){
                    layer.msg("请至少选择一条订单信息进行付汇");return;
                }
                request.post('/scm/client/payment/apply',{payment:payment,orders:orders}).then(res =>{
                    $('#btn-pay-apply-save').off('click');
                    layer.msg('申请成功',{time: 1200},function () {
                        location.hash = '/finance/payList';
                    });
                });
            }
        };
    fn.load();
    $('#btn-pay-apply-save').click(function () {
        fn.saveApply();
    });
    $('#pay-app-payee-name,#pay-app-payee-bank-name').blur(function () {
        fn.fullBankInfo();
    });
    form.on('radio(pay-app-calculation-fee)',function () {
        fn.calculationFee();
    });
    exports('payApply', fn);
});